from Tkinter import Tk, Label, Toplevel, Entry, Button, W, E
from beater import Beater

IDLE='Idle'
START='Start'
STOP='Stop'

class View(object):
   
   def __init__(self, controller):
      self.controller = controller
      self.root = Tk()
      self.make_command_window()
      self.make_activity_window()

   def mainloop(self):
      self.root.mainloop()

   def make_command_window(self):
      f = self.root
      f.title('Command')
      f.geometry('200x150+100+100')
      w = self.start_stop_button = Button(f, text=START, command=self.handle_start_stop)
      w.grid(row=1, column=1, columnspan=2)
      Label(f, text='Enter BPM:').grid(row=2, column=1, sticky=W+E)
      w = self.bpm_entry = Entry(f, text=' ', width=10, bd=0, bg='gray')
      w.grid(row=2, column=2, sticky=W+E)
      w.bind('<Return>', self.handle_set)
      Button(f, text='Set', command=self.handle_set).grid(row=3, column=1, columnspan=2, sticky=W+E)
      delta_bpm = self.controller.delta_bpm
      Button(f, text='<<', command=lambda call=delta_bpm, arg=-1: call(arg)).grid(row=4, column=1, sticky=W+E)
      Button(f, text='>>', command=lambda call=delta_bpm, arg=+1: call(arg)).grid(row=4, column=2, sticky=W+E)

   def make_activity_window(self):
      f = Toplevel()
      f.title('View')
      f.geometry('200x150+100+280')
      Label(f, text='Current BPM:').grid(row=1, column=1)
      w = self.bpm_label = Label(f, text=IDLE)
      w.grid(row=1, column=2)
      w = self.beater = Beater(f)
      w.grid(row=2, column=1, columnspan=2)
      
   def handle_start_stop(self):
      w = self.start_stop_button
      if w.cget('text') == START:
         self.controller.start()
         w.configure(text=STOP)
      else:
         self.controller.stop()
         self.bpm_label.configure(text=IDLE)
         w.configure(text=START)
         
   def handle_set(self, event=None):
      self.controller.set_bpm(int(self.bpm_entry.get()))
      
   def beat_callback(self, what):
      self.beater.set(value=100)
      self.beater.update()
      
   def bpm_callback(self, what):
      if what:
         self.bpm_label.config(text=what)
      else:
         self.bpm_label.config(text=IDLE)
